package com.jxc.action.kcgl;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.jxc.action.BaseAction;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VUser;
import com.jxc.service.GoodsServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/kcgl")
@Action(value = "goodsAmountAction", results = { @Result(name = "goodsAmount", location = "/amountRelate/goodsAmount.jsp") })
public class GoodsAmountAction extends BaseAction implements ModelDriven<VGoods> {

	private VGoods model = new VGoods();

	@Autowired
	private GoodsServiceI goodsService;
	@Autowired
	private UserServiceI userService;
	@Autowired
	private RepertoryServiceI repertoryService;

	public String goodsAmount() {
		getSubAuths("KCGL_KCCX");
		return "goodsAmount";
	}

	public void datagrid() {
		// 查询当前用户所属仓库，将仓库添加到查询条件中
		// 如当前用户没有所属仓库，则查询经销商为当前用户的仓库，将所有仓库中的品牌查询出来
		// 如当前用户没有所属仓库，也没有哪个仓库的经销商为当前用户，则返回为空！
		if (model.getRid() != null) {
			this.writeJson(goodsService.datagrid(model));
		} else {
			SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
			VUser vuser = userService.get(sessionInfo.getUserId());
			if (vuser.getReid() != null) {
				model.setRid(vuser.getReid());
				this.writeJson(goodsService.datagrid(model));
			} else {
				VRepertory vrepertory = new VRepertory();
				vrepertory.setUid(sessionInfo.getUserId());
				List<VRepertory> vrepertories = repertoryService.list(vrepertory);
				if (vrepertories != null && vrepertories.size() > 0) {
					List<VGoods> rows = new ArrayList<VGoods>();
					Long total = 0l;
					for (VRepertory vre : vrepertories) {
						model.setRid(vre.getId());
						DataGrid subDg = goodsService.datagrid(model);
						rows.addAll(subDg.getRows());
						total += subDg.getTotal();
					}
					DataGrid totalDg = new DataGrid();
					totalDg.setRows(rows);
					totalDg.setTotal(total);
					this.writeJson(totalDg);
				} else {
					DataGrid dg = new DataGrid();
					dg.setTotal(0l);
					dg.setRows(new ArrayList<VGoods>());
					this.writeJson(dg);
				}
			}
		}
	}

	@Override
	public VGoods getModel() {
		return model;
	}

}
